package com.android.base.tools;

/**
 * Created by Sammie on 2017/12/24.
 */

import android.app.Activity;
import android.content.Context;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 应用程序Activity管理类：用于Activity管理和应用程序退出
 *
 * @author zwj
 * @version 1.0
 * @created 2015-9-21
 */
public class ActivityManager {
    private static List<Activity> activityStack = new ArrayList<>();

    /**
     * 添加Activity到堆栈
     */
    public static void addActivity(Activity activity) {
        activityStack.add(activity);
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    public static Activity currentActivity() {
        return activityStack.get(activityStack.size() - 1);
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public static void finishCurrentActivity() {
        Activity activity = activityStack.get(activityStack.size() - 1);
        activity.finish();
    }

    /**
     * 结束指定的Activity
     */
    public static void finishActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            if (!activity.isFinishing()) {
                activity.finish();
            }
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public static void finishActivity(Class<?> cls) {
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public static void finishAllActivity() {
        for (Activity activity : activityStack) {
            if (activity != null) {
                activity.finish();
            }
        }
        activityStack.clear();
    }

    /**
     * 结束所有Activity
     */
    public static void finishAllActivityUntil(Class<?> cls) {
        List<Activity> tempActivityStack = new ArrayList<>();
        for (Activity activity : activityStack) {
            if (activity != null && !cls.equals(activity.getClass())) {
                activity.finish();
            }else{
                tempActivityStack.add(activity);
            }
        }
        if(tempActivityStack.isEmpty()){
            activityStack.clear();
        }else {
            Collections.reverse(tempActivityStack);
            activityStack.addAll(tempActivityStack);
        }
    }

    /**
     * 退出应用程序
     */
    public static void AppExit(Context context) {
        try {
            finishAllActivity();
            android.app.ActivityManager manager = (android.app.ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            manager.killBackgroundProcesses(context.getPackageName());
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}